package com.spa.infrastructure.repository.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spa.infrastructure.repository.condition.CouponExchangeCondition;
import com.spa.infrastructure.repository.mapper.CouponExchangeMapper;
import com.spa.infrastructure.repository.po.CouponExchangePO;
import com.spa.infrastructure.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class CouponExchangeRepositoryService extends ServiceImpl<CouponExchangeMapper, CouponExchangePO> {

    public int insert(CouponExchangePO po) {
        return baseMapper.insert(po);
    }

    public long countByCondition(CouponExchangeCondition condition) {
        return count(wrapper(condition));
    }

    public List<CouponExchangePO> listAll(CouponExchangeCondition condition){
        LambdaQueryWrapper<CouponExchangePO> wrapper = wrapper(condition);
        return list(wrapper);

    }

    public Page<CouponExchangePO> page(CouponExchangeCondition condition){
        LambdaQueryWrapper<CouponExchangePO> wrapper = wrapper(condition);
        return page(Page.of(condition.getCurrent(), condition.getSize()), wrapper);

    }

    private LambdaQueryWrapper<CouponExchangePO> wrapper(CouponExchangeCondition condition) {
        LambdaQueryWrapper<CouponExchangePO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StringUtils.isNotEmpty(condition.getCode()), CouponExchangePO::getCode, condition.getCode());
        wrapper.eq(StringUtils.isNotEmpty(condition.getSource()), CouponExchangePO::getSource, condition.getSource());
        wrapper.ge(StringUtils.isNotEmpty(condition.getDestroyBeginTime()), CouponExchangePO::getDestroyTime, condition.getDestroyBeginTime());
        wrapper.ge(StringUtils.isNotEmpty(condition.getCreateBeginTime()), CouponExchangePO::getCreateTime, condition.getCreateBeginTime());
        wrapper.le(StringUtils.isNotEmpty(condition.getDestroyEndTime()), CouponExchangePO::getDestroyTime, condition.getDestroyEndTime());
        wrapper.le(StringUtils.isNotEmpty(condition.getCreateEndTime()), CouponExchangePO::getCreateTime, condition.getCreateEndTime());
        wrapper.orderByDesc(condition.isDestroyTimeDesc(), CouponExchangePO::getDestroyTime);
        return wrapper;
    }

}
